package fox.framework.rpc.server.dispatcher.router;

import fox.framework.rpc.context.definition.RpcDefinition;
import fox.framework.rpc.common.ReflectionUtils;
import fox.framework.rpc.context.RpcObjectFactory;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author cuichao
 * @Description: RpcRouter
 * @Date: create in 2021/1/15 15:31
 */
public class RpcRouter {

    private final ConcurrentMap<String, RouteMapping> mappings = new ConcurrentHashMap<>(128);

    /**
     * 根据path获取路由映射
     * @param path
     * @return
     */
    public RouteMapping getMapping(String path) {
        return mappings.getOrDefault(path, null);
    }

    /**
     * 添加一个路由映射
     * @param mapping
     */
    public void addMapping(RouteMapping mapping){
        mappings.put(mapping.getRoute(),mapping);
    }

    /**
     * 添加
     * @param definition
     */
    public void addMapping(RpcObjectFactory context, RpcDefinition definition ){
        String metaspace = definition.metaspace();
        //find interface method
        Class<?> serviceInterface = definition.serviceInterface();
        List<Method> methods = ReflectionUtils.getAccessibleMethods(serviceInterface);
        //exclude final or static
        methods = ReflectionUtils.excludeStaticOrFinalMethod(methods);
        //foreach to create routeMapping
        for (Method method : methods) {
            String path = String.format("/%s/%s",metaspace,method.getName());
            DefaultRouteMapping mapping = new DefaultRouteMapping(context,path,method,metaspace);
            mappings.put(path,mapping);
        }
    }


    public void clear(){
        mappings.clear();
    }
}
